﻿#include "rollcreatedialog.h"
#include "ui_rollcreatedialog.h"
#include <QSqlQuery>
#include <QSqlTableModel>
#include <QDebug>
#include <QSqlRecord>
#include <QSqlError>
#include <QVariant>
#include <QStringList>
#include <cadremanage/cadreroll.h>
#include <QMessageBox>
#include <QCloseEvent>
#include "cadreutil.h"
#include "timeeditdelegate.h"

RollCreateDialog::RollCreateDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::RollCreateDialog)
{
    ui->setupUi(this);
    cadreSearchDialog = new RollCadreSearchDialog(this);
    addId=0;  //初始化为0，不初始化则是随机的，不方便后边添加操作的处理
}

RollCreateDialog::~RollCreateDialog()
{
    delete ui;
}

void RollCreateDialog::on_cancelButton_clicked()
{
   if(addId){
       QSqlQuery query;
       query.exec(QString::fromUtf8("DELETE FROM Roll WHERE `RollID`=%1").arg(addId));
   }
   this->reject();
   delete this;
}

void RollCreateDialog::on_addButton_clicked()
{
    if(addId==0){
       saveRoll();
    }
    cadreSearchDialog->exec();
}
void RollCreateDialog::receiveIdData(QStringList ids)
{
    if(!ids.isEmpty()){
         initTable();
    }
}

void RollCreateDialog::initTable()
{
    QString sql = QString::fromUtf8("SELECT `CadreName`, `UsedName`, cc.`CredType`, ci.`IDNum`, "
                  "`Birth`, `JoinWorkTime`, `Sex`, `Health`, nationc.`Nation`, "
                  "`NativePlace`, `BirthPlace`, `GrowPlace`, politicc.`Politic`, "
                  "`PartyTime`,`DemoParty`, `RetireChange`, `Speciality`, "
                  "msc.`ManageStatus`, `IdenCate`, `ThreeOne`, `Phone`, "
                  "`SubstratumWork`, uc.unitname,rc.`RankName`, `RankTime`, "
                  "`RankSalary`, `Photo` "
                  "FROM ZZB.CadreRollRelation crr "
                  "left join ZZB.CadreInfo ci on crr.`IDNum`=ci.`IDNum` "
                  "left join ZZB.CredTypeCode cc on ci.`CredTypeID`= cc.`CredTypeID` "
                  "left join ZZB.NationCode nationc on nationc.`NationID`=ci.`NationID` "
                  "left join ZZB.PoliticCode politicc on politicc.`PoliticID`=ci.`PoliticID` "
                  "left join ZZB.ManageStatusCode msc on msc.`ManageStatusID`=ci.`ManageStatusID` "
                  "left join ZZB.unit uc on uc.`UnitID`=ci.`UnitID` "
                  "left join ZZB.RankCode rc on rc.`RankID`=ci.`RankID` "
                  "where `RollID`= %1").arg(addId);
    tableModel = new ResultTableModel(this);
    tableModel->setQuery(sql);
    tableModel->setHeaderData(0, Qt::Horizontal, QString::fromUtf8("姓名"));
    tableModel->setHeaderData(3, Qt::Horizontal, QString::fromUtf8("证件号码"));
    tableModel->setHeaderData(4, Qt::Horizontal, QString::fromUtf8("生日"));
    tableModel->setHeaderData(6, Qt::Horizontal, QString::fromUtf8("性别"));
    ui->cadreRollTable->setModel(tableModel);
    ui->cadreRollTable->horizontalHeader()->setVisible(true);

    TimeEditDelegate *birthtime = new TimeEditDelegate();
    ui->cadreRollTable->setItemDelegateForColumn(4,birthtime);
    tableModel->chash["Sex"]=6; //性别的列数

    for(int i=0;i< (tableModel->columnCount());i++){
        if(i==0|| i==3 || i==4 || i==6){
        }else{
            ui->cadreRollTable->setColumnHidden(i,true);
        }
    }
    ui->cadreRollTable->show();
}

void RollCreateDialog::saveRoll()
{
    QSqlQuery query;
    // rolltype 0是单位，1是干部
    query.prepare("INSERT INTO Roll (`RollDate`, `RollName`, `RollType`) "
                  "VALUES(:rolldate, :rollname, '1');");
    query.bindValue(":rolldate",ui->rollDateEdit->date());
    query.bindValue(":rollname",ui->nameLineEdit->text());
    if(query.exec()){
        addId = query.lastInsertId().toInt();
    }
}
void RollCreateDialog::updateRoll()
{
    QSqlQuery query;
    // rolltype 0是单位，1是干部
    query.prepare("UPDATE Roll SET `RollDate`=:rolldate, `RollName`=:rollname "
                  "WHERE `RollID`= :id ;");
    query.bindValue(":rolldate",ui->rollDateEdit->date());
    query.bindValue(":rollname",ui->nameLineEdit->text());
    query.bindValue(":id",addId);
    if(query.exec()){
        qDebug()<< query.lastError().text();
    }
}
void RollCreateDialog::on_saveButton_clicked()
{
    //不可能有那个rollID为0
    if(addId==0){
        saveRoll();
    }else{
        updateRoll();
    }
    CadreRoll *p =(CadreRoll*)parentWidget();
    p->initTableView();
    this->reject();
    delete this;
}

void RollCreateDialog::closeEvent(QCloseEvent *event)
{
    QMessageBox::StandardButton button;
    button = QMessageBox::question(this, trUtf8("确定退出"),
        QString(trUtf8("是否结束操作退出?")),
        QMessageBox::Yes | QMessageBox::No);

    if (button == QMessageBox::No) {
        event->ignore();
    }
    else if (button == QMessageBox::Yes) {
        event->accept();
        on_cancelButton_clicked(); //与取消按钮行为一致
    }
}

QSqlTableModel* RollCreateDialog::getOriginalModel()
{
    QSqlTableModel *originalmodel = new QSqlTableModel(this);
    originalmodel->setTable("CadreRollRelation");
    QString filter = QString::fromUtf8("RollID='%1'").arg(addId);
    originalmodel->setFilter(filter);
    originalmodel->select();
    originalmodel->setEditStrategy(QSqlTableModel::OnFieldChange);
    return originalmodel;
}

void RollCreateDialog::on_deleteButton_clicked()
{
    if(ui->cadreRollTable->rowAt(0)==-1){
        return;
    }
    int index = ui->cadreRollTable->currentIndex().row();
    QString selectIdNum = (tableModel->record(index)).value("IDNum").toString();
    QSqlQuery query;
    QString sql = QString::fromUtf8("delete from CadreRollRelation where RollID=:rollid "
                                    "and IDNum=:idnum");
    query.prepare(sql);
    query.bindValue(":rollid", addId);
    query.bindValue(":idnum", selectIdNum);
    if(query.exec()) {
        initTable();
    }else {
        QMessageBox::information(this,trUtf8("操作提示"),
            trUtf8("操作失败"),QMessageBox::Yes);
    }
}

void RollCreateDialog::on_upButton_clicked()
{
    QSqlTableModel *originalmodel = getOriginalModel();
    int cur = CadreUtil::moveUpOne(originalmodel,0,ui->cadreRollTable);
    initTable();
    ui->cadreRollTable->selectRow(cur);
}

void RollCreateDialog::on_downButton_clicked()
{
    QSqlTableModel *originalmodel = getOriginalModel();
    int cur = CadreUtil::moveDownOne(originalmodel,0,ui->cadreRollTable);
    initTable();
    ui->cadreRollTable->selectRow(cur);
}
